package spring.aop.proxy;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * @author cg
 * @date 2023/6/18 21:36
 */
public class CglibChain {
    //切面链
    private List<CglibPoint> cglibPoints;

    //责任链开始的位置
    private int idx = -1;
    //被代理对象
    private Object target;

    public CglibChain(Object target) {
        this.target = target;
        this.cglibPoints = new ArrayList<>();
    }

    public void registCglibPoint(CglibPoint cglibPoint) {
        cglibPoints.add(cglibPoint);
    }

    /**
     * 执行代理链
     * @param method 被代理方法
     * @param args 被代理方法参数
     * @return
     */
    public Object process(Method method, Object[] args) {
        Object res = null;
        //没有责任链了就直接返回
        if (++idx ==cglibPoints.size()){
            try {
                res = method.invoke(target, args);
            } catch (IllegalAccessException | InvocationTargetException e) {
                throw new RuntimeException(e);
            }
//            System.out.println("cglib代理结束");
        }else {
            res = cglibPoints.get(idx).proceed(this, method, args);
        }
        return res;
    }

    public void resetIdx() {
        this.idx = -1;
    }
}
